
$(function () {

    $('#groupHide').click(function () {
        $('#hideGroup').hide();
        $('#groupHide').hide();
        $('#groupShow').show();
    });

    $('#groupShow').click(function () {
        $('#hideGroup').show();
        $('#groupHide').show();
        $('#groupShow').hide();
    });


    $('#establishDateStart').datepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        autoclose:true
    });
    $('#establishDateEnd').datepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        autoclose:true
    });
    $('#singDateStart').datepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        autoclose:true
    });
    $('#singDateEnd').datepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd',
        autoclose:true
    });

    getParamsByparamTypeValue('contractType', "#contractType");
    getParamsByparamTypeValue('projectStatus', "#projectStatus");
    getParamsByparamTypeValue('projectType', "#projectType");


    $('#directExpenses,#salesExpenses,#implementExpenses,#procurementExpenses,#manageExpenses').keyup(function(){
        reckon();
    });


    $('#save').click(function () {
        $.ajax({
            type: "POST",
            contentType:"application/json",
            url: ctx + "/estimate/save",
            data:JSON.stringify($('form').serializeJson()),
            success: function(data){
                if(data.code==200){
                    alert(data.data);
                }else{
                    alert(data.msg);
                }
                window.location.href = 'list.html';
            }
        });
    });


    initTable();

    $('#search').click(function(){
        $('#groupValue').val("");
        //先销毁表格
        $('#table').bootstrapTable('destroy');
        //初始化表格
        initTable();
    });

    $('#export').click(function () {
        $(this).button('loading').delay(1000).queue(function() {
            $('#table').tableExport({ignoreColumn: [21],type:'excel',fileName: '项目盈利分析', excelstyles:['border-bottom', 'border-top', 'border-left', 'border-right']});

            /*confirm('提示', '你确定要导出Excel电子表格吗？', function exportExcel(){
                window.location.href = ctx + '/estimate/exportProfit' + '?' + $.param(exportParams());
            });*/
            $(this).button('reset');
            $(this).dequeue();
        });
    });
});


function groupBy(value) {
    $('#groupValue').val(value);
    //先销毁表格
    $('#table').bootstrapTable('destroy');
    //初始化表格
    initTable();
    switch (value) {
        case 'all' :
            $('#table').bootstrapTable('showColumn','count');
            break;
        case 'org' :
            $('#table').bootstrapTable('showColumn','linkSalerOrgName');
            $('#table').bootstrapTable('showColumn','count');
            break;
        case 'manager' :
            $('#table').bootstrapTable('showColumn','linkManagerName');
            $('#table').bootstrapTable('showColumn','count');
            break;
        default :
    }

    $('#table').bootstrapTable('hideColumn','projectCode');
    $('#table').bootstrapTable('hideColumn','projectName');
    $('#table').bootstrapTable('hideColumn','projectStatusName');
    $('#table').bootstrapTable('hideColumn','salerOrgName');
    $('#table').bootstrapTable('hideColumn','salerName');
    $('#table').bootstrapTable('hideColumn','managerName');
    $('#table').bootstrapTable('hideColumn','createDate');
    $('#table').bootstrapTable('hideColumn','singDate');
    $('#table').bootstrapTable('hideColumn','expectedFinalDate');
    $('#table').bootstrapTable('hideColumn','operations');

    $('.fixed-table-body').addClass('table-responsive');

}


function loadModal(type,projectId) {
    if(type==0){
        $('#save').hide();
        $('#directExpenses').attr('readonly','readonly');
        $('#salesExpenses').attr('readonly','readonly');
        $('#implementExpenses').attr('readonly','readonly');
        $('#procurementExpenses').attr('readonly','readonly');
    }else{
        $('#save').show();
        $('#directExpenses').removeAttr('readonly');
        $('#salesExpenses').removeAttr('readonly');
        $('#implementExpenses').removeAttr('readonly');
        $('#procurementExpenses').removeAttr('readonly');
    }
    $.ajax({
        type: "POST",
        url: ctx + "/estimate/queryProfit",
        data:{
            projectId: projectId
        },
        success: function(data){
            if(data.code == 200){
                var value = data.data.rows[0];
               // $("#id").val(data.data.id);
                $("#directExpenses").val(Number(value.directExpenses).toFixed(2));
                $("#salesExpenses").val(Number(value.salesExpenses).toFixed(2));
                $("#implementExpenses").val(Number(value.implementExpenses).toFixed(2));
                $("#procurementExpenses").val(Number(value.procurementExpenses).toFixed(2));
                $("#manageExpenses").val(Number(value.manageExpenses).toFixed(2));
                $("#projectId").val(value.projectId);
                //$("#description").val(value.description.toFixed(2));
                $("#totalNonTaxAmount").val(Number(value.totalNonTaxAmount).toFixed(2));
                $("#paymentAmount").val(Number(value.paymentAmount).toFixed(2));
                $("#procurementAmount").val(Number(value.procurementAmount).toFixed(2));
                $("#projectCost").val(Number(value.projectCost).toFixed(2));
                $("#directAmount").val(Number(value.directAmount).toFixed(2));
                $("#indirectAmount").val(Number(value.indirectAmount).toFixed(2));
                $("#actualCost").val(Number(value.actualCost).toFixed(2));
                $("#needCost").val(Number(value.needCost).toFixed(2));
                $("#totalCost").val(Number(value.totalCost).toFixed(2));
                $("#profitCost").val(Number(value.profitCost).toFixed(2));
            }else{
                alert(data.msg);
            }
        }
    });
}

function reckon(){
    var needCost = (Number($('#directExpenses').val())+Number($('#salesExpenses').val())+Number($('#implementExpenses').val())+Number($('#procurementExpenses').val())+Number($('#manageExpenses').val())).toFixed(2);
    $('#needCost').val(needCost);
    $('#totalCost').val((Number(needCost)+Number($('#actualCost').val())).toFixed(2));
    $('#profitCost').val(Number($('#totalNonTaxAmount').val())-Number($('#totalCost').val()));
}

function  initTable() {
    $('#table').bootstrapTable({
        height:top.frameHeight*0.7,
        url: ctx + '/estimate/queryProfit', //这个接口需要处理bootstrap table传递的固定参数
        method:'post',
        dataType: "json",
        cache: false,   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",   //post请求,content type默认设置为 text/plain,在服务端直接通过 @RequestParam参数映射是获取不到的。
        striped: true,      //是否显示行间隔色
        pagination: true,     //是否显示分页（*）
        singleSelect: true,  //单选
        sortable: false,      //是否启用排序
        sortOrder: "asc",     //排序方式
        pageNumber:1,      //初始化加载第一页，默认第一页
        pageSize: 10,      //每页的记录行数（*）
        pageList: [10, 25, 50, 100 ,'All'],  //可供选择的每页的行数（*）
        queryParamsType:'',  //默认值为 'limit' ,在默认情况下 传给服务端的参数为：offset,limit,sort
        //设置为 ''  在这种情况下传给服务器的参数为：pageSize,pageNumber
        queryParams : queryParams,    //前端调用服务时，会默认传递上边提到的参数，如果需要添加自定义参数，可以自定义一个函数返回请求参数
        sidePagination: "server",   //分页方式：client客户端分页，server服务端分页（*）
        responseHandler:function(res){
            //远程数据加载之前,处理程序响应数据格式,对象包含的参数: 我们可以对返回的数据格式进行处理
            //在ajax后我们可以在这里进行一些事件的处理
            if(res.data.rows[0]==null){
                res.data.rows = [];
            }

            return res.data;
        },
        onLoadSuccess:function () {

        },
        strictSearch: true,
        clickToSelect: true,    //是否启用点击选中行
        searchOnEnterKey: true,
        showFooter: true,
        columns: [{
            title: '序号',  //标题  可不加
            width: 50,
            align: 'center',
            formatter: function (value, row, index) {
                var pageNumber = $('#table').bootstrapTable('getOptions').pageNumber;
                var pageSize = $('#table').bootstrapTable('getOptions').pageSize == 'All' ? 0 : $('#table').bootstrapTable('getOptions').pageSize;
                return (pageNumber-1) * pageSize+index+1;
            },
            footerFormatter: function (value) {
                return '合计';
            }
        }, {
            field: 'linkSalerOrgName',
            title: '销售部门',
            align: 'center',
            width: 100,
            visible: false,
            formatter: function (value, row, index) {
                return '<a class="page-action" href="#" role="button" title="SD-'+row.salerOrgName+'" data-id="Estimate/subList/SD'+row.salerOrgName+'"  data-href="Estimate/subList.html?projectIds='+row.projectIds+'&groupBy=sale&parentPageId='+top.topManager.getPageId()+'">'+row.salerOrgName+'</a>';
            }
        }, {
            field: 'linkManagerName',
            title: '项目经理',
            align: 'center',
            width: 100,
            visible: false,
            formatter: function (value, row, index) {
                return '<a class="page-action" href="#" role="button" title="PM-'+row.managerName+'" data-id="Estimate/copyList/PM'+row.managerName+'"  data-href="Estimate/copyList.html?projectIds='+row.projectIds+'&parentPageId='+top.topManager.getPageId()+'">'+row.managerName+'</a>';
            }
        }, {
            field: 'count',
            title: '项目个数',
            align: 'center',
            width: 80,
            visible: false,
            formatter: function (value, row, index) {
                return row.projectIds.split(',').length;
            }
        }, {
            field: 'projectCode',
            align: 'center',
            width: 100,
            title: '项目编号'
        },{
            field: 'projectName',
            align: 'center',
            width: 300,
            title: '项目名称'
        },{
            field: 'projectStatusName',
            align: 'center',
            width: 100,
            title: '项目状态'
        },{
            field: 'totalContractAmount',
            align: 'right',
            width: 130,
            title: '合同总金额',
            formatter: function (value, row, index) {
                //格式化金额
                return formatMoney(value);
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].totalContractAmount);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'taxPaymentAmount',
            align: 'right',
            width: 100,
            title: '已收款',
            formatter: function (value, row, index) {
                //格式化金额
                return formatMoney(value);
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].taxPaymentAmount);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'taxUnpaymentAmount',
            align: 'right',
            width: 100,
            title: '未收款',
            formatter: function (value, row, index) {
                //格式化金额
                return formatMoney(value);
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].taxUnpaymentAmount);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'totalNonTaxAmount',
            align: 'right',
            width: 130,
            title: '不含税合同总金额',
            formatter: function (value, row, index) {
                //格式化金额
                return formatMoney(value);
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].totalNonTaxAmount);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'paymentAmount',
            align: 'right',
            width: 100,
            title: '已结转收入',
            formatter: function (value, row, index) {
                //格式化金额
                return formatMoney(value);
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].paymentAmount);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'unpaymentAmount',
            align: 'right',
            width: 100,
            title: '未结转收入',
            formatter: function (value, row, index) {
                //格式化金额
                return formatMoney(value);
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].unpaymentAmount);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'actualCost',
            align: 'right',
            width: 100,
            title: '已发生成本',
            formatter:function (value, row, index) {
                if(row.directAmount==0&&row.indirectAmount==0&&row.procurementAmount==0&&row.projectCost==0){
                    return value;
                }else{
                    var groupValue = $('#groupValue').val();
                    if(groupValue==''){
                        return '<a class="page-action" href="#" role="button" title="'+row.projectCode+'项目成本" data-id="Estimate/actual/project/'+row.projectCode+'" data-href="Estimate/actual.html?projectName='+encodeURI(row.projectName)+'&projectId='+row.projectId+'&actualCost='+row.actualCost+'&type=project&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(value)+'</a>';
                    }else{
                        var projectName = '';
                        var title = '';
                        switch(groupValue)
                        {
                            case 'org':
                                title = row.salerOrgName + '-项目成本';
                                projectName = row.salerOrgName + '项目';
                                break;
                            case 'manager':
                                title = row.managerName + '-负责项目成本';
                                projectName = row.managerName + '负责项目';
                                break;
                            case 'all':
                                title = '公司项目成本';
                                projectName = '公司项目';
                                break;
                        }
                        return '<a class="page-action" href="#" role="button" title="'+title +'" data-id="Estimate/actual/'+title+'"  data-href="Estimate/actual.html?projectName='+encodeURI(projectName)+'&projectId='+row.projectIds+'&actualCost='+row.actualCost+'&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(value)+'</a>';
                    }
                }
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].actualCost);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'actualProfit',
            title: '已实现利润',
            align: 'right',
            width: 100,
            formatter: function (value, row, index) {
                if(row.paymentAmount==0&&row.actualCost==0){
                    return formatMoney(row.paymentAmount-row.actualCost);
                }else{
                    //格式化金额
                    if(row.paymentAmount-row.actualCost < 0 ){
                        return '<a class="page-action red" href="#" role="button" title="'+row.projectCode+'已实现利润" data-id="Estimate/profit/project/'+row.projectCode+'" data-href="Estimate/actualProfit.html?projectName='+encodeURI(row.projectName)+'&projectId='+row.projectId+'&profitCost='+row.profitCost+'&type=project&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(row.paymentAmount-row.actualCost)+'</a>';
                    }else{
                        return '<a class="page-action" href="#" role="button" title="'+row.projectCode+'已实现利润" data-id="Estimate/profit/project/'+row.projectCode+'" data-href="Estimate/actualProfit.html?projectName='+encodeURI(row.projectName)+'&projectId='+row.projectId+'&profitCost='+row.profitCost+'&type=project&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(row.paymentAmount-row.actualCost)+'</a>';
                    }
                }
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=value[i].paymentAmount - value[i].actualCost;
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        }, {
            field: 'needCost',
            align: 'right',
            width: 100,
            title: '预计尚需成本',
            formatter:function (value, row, index) {
                if(row.costEstimateAmount==0&&row.directEstimateAmount==0&&row.indirectEstimateAmount==0&&row.procurementEstimateAmount==0){
                    return value;
                }else{
                    var groupValue = $('#groupValue').val();

                    if(groupValue==''){
                        return '<a class="page-action" href="#" role="button" title="'+row.projectCode+'项目预计尚需成本" data-id="Estimate/need/project/'+row.projectCode+'" data-href="Estimate/needCost.html?projectName='+encodeURI(row.projectName)+'&projectId='+row.projectId+'&needCost='+row.needCost+'&type=project&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(value)+'</a>';
                    }else{
                        var projectName = '';
                        var title = '';
                        switch(groupValue)
                        {
                            case 'org':
                                title = row.salerOrgName + '-项目预计尚需成本';
                                projectName = row.salerOrgName + '项目';
                                break;
                            case 'manager':
                                title = row.managerName + '-负责预计尚需成成本';
                                projectName = row.managerName + '负责项目';
                                break;
                            case 'all':
                                title = '公司项目预计尚需成';
                                projectName = '公司项目';
                                break;
                        }
                        return '<a class="page-action" href="#" role="button" title="'+title +'" data-id="Estimate/need/'+title+'"  data-href="Estimate/needCost.html?projectName='+encodeURI(projectName)+'&projectId='+row.projectIds+'&needCost='+row.needCost+'&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(value)+'</a>';
                    }
                }
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].needCost);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'totalCost',
            align: 'right',
            width: 100,
            title: '预计总成本',
            formatter: function (value, row, index) {
                if(row.actualCost==0&&row.needCost==0){
                    return value;
                }else{
                    var groupValue = $('#groupValue').val();
                    if(groupValue==''){
                        return '<a class="page-action" href="#" role="button" title="'+row.projectCode+'预计总成本" data-id="Estimate/total/project/'+row.projectCode+'" data-href="Estimate/totalCost.html?projectName='+encodeURI(row.projectName)+'&projectId='+row.projectId+'&ProjectTotalCost='+value+'&type=project&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(value)+'</a>';
                    }else{
                        var projectName = '';
                        var title = '';
                        switch(groupValue)
                        {
                            case 'org':
                                title = row.salerOrgName + '-预计总成本';
                                projectName = row.salerOrgName + '项目';
                                break;
                            case 'manager':
                                title = row.managerName + '-负责预计总成本';
                                projectName = row.managerName + '负责项目';
                                break;
                            case 'all':
                                title = '公司项目预计总成本';
                                projectName = '公司项目';
                                break;
                        }
                        return '<a class="page-action" href="#" role="button" title="'+title +'" data-id="Estimate/total/'+title+'"  data-href="Estimate/totalCost.html?projectName='+encodeURI(projectName)+'&projectId='+row.projectIds+'&ProjectTotalCost='+value+'&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(value)+'</a>';
                    }
                }
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].totalCost);
                }

                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'profitCost',
            align: 'right',
            width: 100,
            title: '预计利润',
            formatter: function (value, row, index) {
                if(row.estimatePayment==0&&row.paymentAmount==0&&row.totalCost==0){
                    return value;
                }else{
                    var flag = Math.round(row.totalNonTaxAmount-row.totalCost) != Math.round(row.estimatePayment+row.paymentAmount-row.totalCost);
                    var groupValue = $('#groupValue').val();
                    if(groupValue==''){
                        var color = '';
                        if(flag){
                            color = 'green';
                        }else if(value< 0){
                            color = 'red';
                        }
                        return '<a class="page-action '+color+'" href="#" role="button" title="'+row.projectCode+'预计利润" data-id="Estimate/profit/project/'+row.projectCode+'" data-href="Estimate/profit.html?projectName='+encodeURI(row.projectName)+'&projectId='+row.projectId+'&profitCost='+row.profitCost+'&type=project&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(value)+'</a>';
                    }else{
                        var projectName = '';
                        var title = '';
                        switch(groupValue)
                        {
                            case 'org':
                                title = row.salerOrgName + '-预计利润';
                                projectName = row.salerOrgName + '项目';
                                break;
                            case 'manager':
                                title = row.managerName + '-负责预计利润';
                                projectName = row.managerName + '负责项目';
                                break;
                            case 'all':
                                title = '公司项目预计利润';
                                projectName = '公司项目';
                                break;
                        }
                        var color = '';
                        if(flag){
                            color = 'green';
                        }else if(value< 0){
                            color = 'red';
                        }

                        return '<a class="page-action '+color+'" href="#" role="button" title="'+title +'" data-id="Estimate/profit/'+title+'"  data-href="Estimate/profit.html?projectName='+encodeURI(projectName)+'&projectId='+row.projectIds+'&profitCost='+row.profitCost+'&parentPageId='+top.topManager.getPageId()+'">'+formatMoney(value)+'</a>';
                    }
                }
            },
            footerFormatter: function (value) {
                var sum = 0;
                for(var i in value){
                    sum+=Number(value[i].profitCost);
                }
                return sum<0?'<span style="color:red">' + formatMoney(sum) + '</span>':formatMoney(sum);
            }
        },{
            field: 'singDate',
            align: 'center',
            width: 100,
            title: '签订日期',
            formatter: function (value, row, index) {
                return $.myTime.UnixToDate(Number(value));
            }
        },{
            field: 'expectedFinalDate',
            align: 'center',
            width: 100,
            title: '预计终验日期',
            formatter: function (value, row, index) {
                return $.myTime.UnixToDate(Number(value));
            }
        },{
            field: 'salerOrgName',
            align: 'center',
            width: 100,
            title: '销售部门'
        }, {
            field: 'salerName',
            align: 'center',
            width: 100,
            title: '销售人员'
        }, {
            field: 'managerName',
            align: 'center',
            width: 100,
            title: '项目经理'
        }]
    });

}
function queryParams(params){
    var loginCode = window.sessionStorage.getItem("managerUser");
    return {
        pageNumber : params.pageNumber,
        pageSize : params.pageSize,
        establishDateStart : $('#establishDateStart').val(),
        establishDateEnd : $('#establishDateEnd').val(),
        singDateStart : $('#singDateStart').val(),
        singDateEnd : $('#singDateEnd').val(),
        customerName : $('#customerName').val(),
        saleName : $('#saleName').val(),
        saleOrg : $('#saleOrg').val(),
        contractType : $('#contractType').val(),
        contractName : $('#contractName').val(),
        projectCode : $('#projectCode').val(),
        projectName : $('#projectName').val(),
        managerName : $('#managerName').val(),
        projectStatus:$('#projectStatus').val(),
        projectType:$('#projectType').val(),
        groupBy:$('#groupValue').val(),
        loginCode : loginCode
    }
}

/*function exportParams() {
    var loginCode = window.sessionStorage.getItem("managerUser");
    return {
        establishDateStart : $('#establishDateStart').val(),
        establishDateEnd : $('#establishDateEnd').val(),
        singDateStart : $('#singDateStart').val(),
        singDateEnd : $('#singDateEnd').val(),
        customerName : $('#customerName').val(),
        saleName : $('#saleName').val(),
        saleOrg : $('#saleOrg').val(),
        contractType : $('#contractType').val(),
        contractName : $('#contractName').val(),
        projectCode : $('#projectCode').val(),
        projectName : $('#projectName').val(),
        managerName : $('#managerName').val(),
        projectStatus:$('#projectStatus').val(),
        loginCode : loginCode
    }
}*/



